import { post } from "../customUtils";
import { ChatMsg } from "./type";

function msgFn(ctn = '') {
	if (!ctn) return;
	uni.showToast({ title: ctn, icon: 'none' })
}

/** chat 数据相关 */
const state = {
	/** 
	 * @property {Array<ConverationItem>} 会话列表
	 */
	conversationList: [],
	/** 
	 * 消息对象
	 * @property {Object} 消息对象 {会话id<String>: {page:Number, list: 消息列表Array<ChatMsg>}}
	 * @example {11: {page:1, list:[]}}
	 */
	msgInfos: {},
	/** 当前消息列表 Array<ConverationItem> */
	currentMsgList: [],
	/** 当前会话ID */
	currentConvarsationId: "",
};

const actions = {
	/** 创建新会话 */
	async createConversation() {
		try {
			await post('', {});
			await dispatch('getConversationList');
		} catch (e) { msgFn(e.msg) }
	},
	/** 获取会话列表 */
	async getConversationList({ state, commit }) {
		try {
			const res = await post('', {});
			state.conversationList = (res.data || []).map(item => new ConverationItem(item));
			commit('setCurrentMsgList');
		} catch (e) { msgFn(e.msg) }
	},
	/** 更新会话列表名称 */
	async getConversationName({ dispatch }, val) {
		try {
			await post('', {});
			console.debug('操作会话列表名称数据')
		} catch (e) { msgFn(e.msg) }
	},
	/** 删除指定会话 */
	async removeConversationById({ dispatch }, id) {
		try {
			await post('', {});
			await dispatch('getConversationList');
		} catch (e) { msgFn(e.msg) }
	},
	/** 对当前消息列表添加消息api数据存储【接口完全返回后调用】 */
	async addMsgByConversationId(state, info = {}) {
		console.debug('当前会话ID' + state.currentConvarsationId)
		try {
			await post('', {});
		} catch (e) { msgFn(e.msg) }
	},
	/** 删除全部会话 */
	async removeAllConversation(state, info = {}) {
		try {
			await post('', {});
			state.conversationList = [];
			state.currentMsgList = [];
		} catch (e) { msgFn(e.msg) }
	},
}

const mutations = {
	/** 初始化当前会话消息列表 */
	setCurrentMsgList(state) { console.debug('set current msg list') },
	/** 切换当前会话 */
	async changeCurrentConversation(state, id = '') {
		if (!id) throw 'change current msg list';
		state.currentMsgList = state.msgInfos[id];
	},
};

export default { state, mutations, actions }